package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.Role;
import com.xmy.cultivate.service.IRoleService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-08-07
 */
@RestController
@RequestMapping("/api/role")
@Scope("prototype")
public class RoleController extends BaseController{
    @Autowired
    IdWorker idWorker;

    @Autowired
    IRoleService iRoleService;

    @GetMapping("")
    public Result findAll(@RequestParam Map reMap){
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        List<Role> roleList = iRoleService.list(queryWrapper);
        return new Result(Code.OK,roleList);
    }

    @GetMapping("allRole")
    public Result allRole(@RequestParam Map reMap){
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        List<Role> roleList = iRoleService.allRole(queryWrapper);
        //return Result(new )
        return new Result(Code.OK,new PageResult(roleList,1L,1L));
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") String id){
        try{
            Role role = iRoleService.getById(id);
            return new Result(Code.OK,role);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody Role role){
        boolean rs = iRoleService.saveTo(role);
        return new Result(rs?Code.OK:Code.ERROR);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Role role){
        try{
            boolean rs = iRoleService.updateById(role);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
        try{
            boolean rs =  iRoleService.removeById(id);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }
}
